﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;

namespace LFMTest
{
    public sealed partial class SearchResults
    {
        String queryText;

        ObservableCollection<lfm.Artist> ArtistCollection = new ObservableCollection<lfm.Artist>();
        ObservableCollection<lfm.Album> AlbumCollection = new ObservableCollection<lfm.Album>();
        ObservableCollection<lfm.Track> TrackCollection = new ObservableCollection<lfm.Track>();

        public SearchResults()
        {
            InitializeComponent();

            
        }
        
        public void Activate(SearchActivatedEventArgs args)
        {
            queryText = args.QueryText;

            //TODO: Application-specific searching logic

            // Prepare bindable content
            var bindableProperties = new PropertySet();
            bindableProperties["QueryText"] = '"' + queryText + '"';
            this.DataContext = bindableProperties;

            // Display the results
            this.PreviousContent = Window.Current.Content;
            Window.Current.Content = this;
            Window.Current.Activate();

            ArtistPanel.ItemsSource = ArtistCollection;
            AlbumPanel.ItemsSource = AlbumCollection;
            TrackPanel.ItemsSource = TrackCollection;

            Search();
        }

        #region State Management

        private UIElement _priorContent;
        UIElement PreviousContent
        {
            get { return _priorContent; }
            set
            {
                this._priorContent = value;
                BackButton.IsEnabled = value != null;
            }
        }

        void BackButton_Click(object sender, RoutedEventArgs e)
        {
            Window.Current.Content = PreviousContent;
            Window.Current.Activate();
        }


        // View state management for switching among Full, Fill, Snapped, and Portrait states

        private DisplayPropertiesEventHandler _displayHandler;
        private TypedEventHandler<ApplicationLayout, ApplicationLayoutChangedEventArgs> _layoutHandler;

        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            DisplayProperties.OrientationChanged -= _displayHandler;
            ApplicationLayout.GetForCurrentView().LayoutChanged -= _layoutHandler;
        }

        private void Page_LayoutChanged(object sender, ApplicationLayoutChangedEventArgs e)
        {
            SetCurrentOrientation(this);
        }

        private void Page_OrientationChanged(object sender)
        {
            SetCurrentOrientation(this);
        }

        private void SetCurrentOrientation(Control viewStateAwareControl)
        {
            VisualStateManager.GoToState(viewStateAwareControl, this.GetViewState(), false);
        }

        private String GetViewState()
        {
            var orientation = DisplayProperties.CurrentOrientation;
            if (orientation == DisplayOrientations.Portrait ||
                orientation == DisplayOrientations.PortraitFlipped) return "Portrait";
            var layout = ApplicationLayout.Value;
            if (layout == ApplicationLayoutState.Filled) return "Fill";
            if (layout == ApplicationLayoutState.Snapped) return "Snapped";
            return "Full";
        }

        #endregion


        private async void Search()
        {
            pRing.IsActive = true;

            AlbumPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            ArtistPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            TrackPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

            if (filter.SelectedIndex == 0)
            {
                foreach (var a in await lfm.EndPoints.Artist.search(queryText, null, 30)) ArtistCollection.Add(a);
                ArtistPanel.Visibility = Windows.UI.Xaml.Visibility.Visible;
                pRing.IsActive = false;

                foreach (var a in await lfm.EndPoints.Artist.search(queryText, 1, 30)) ArtistCollection.Add(a);
            }
            else if (filter.SelectedIndex == 1)
            {
                AlbumCollection.AddIEnumerable<lfm.Album>(await lfm.EndPoints.Album.search(queryText, null, 30));
                AlbumPanel.Visibility = Windows.UI.Xaml.Visibility.Visible;
                pRing.IsActive = false;

                AlbumCollection.AddIEnumerable<lfm.Album>(await lfm.EndPoints.Album.search(queryText, 1, 30));
            }
            else if (filter.SelectedIndex == 2)
            {
                TrackCollection.AddIEnumerable<lfm.Track>(await lfm.EndPoints.Track.search(queryText, null, null, 30));
                TrackPanel.Visibility = Windows.UI.Xaml.Visibility.Visible;
                pRing.IsActive = false;

                TrackCollection.AddIEnumerable<lfm.Track>(await lfm.EndPoints.Track.search(queryText, null, 1, 30));
            }
        }

        private Int32 NextPage(Int32 count)
        {
            return 30 % count;
        }

        private void filter_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Search();
        }
    }
}
